package cn.jinzhu.netty.server.handler;

import cn.jinzhu.netty.message.ChatRequestMessage;
import cn.jinzhu.netty.message.ChatResponseMessage;
import cn.jinzhu.netty.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.internal.StringUtil;
import org.springframework.util.StringUtils;

import java.util.Objects;
//SimpleChannelInboundHandler 指定接收某个类型
//使用该类表示在netty中可以被其他线程共享 因为这类没用什么变量是不能被共享的
@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        String to = msg.getTo();
        //找到用户的channel
        Channel channel = SessionFactory.getSession().getChannel(to);
        //判断是否在线  在线获取该用户让他发送消息
        if (!Objects.equals(null,channel)) {
            channel.writeAndFlush(new ChatResponseMessage(msg.getFrom(), msg.getContent()));
        } else {
            //如果不在线 服务器channel发送消息提示不在线
            ctx.writeAndFlush(new ChatResponseMessage(false, "对方用户不在线"));
        }
    }
}
